package com.sky.aspect;

import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自动新增注入
 *
 * @author liudo
 * @version 1.0
 * @project sky-take-out
 * @date 2024/2/4 09:16:24
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("@annotation(com.sky.annotation.AutoInsertFill)")
    public void insert() {

    }


    @Before("insert()")
    public void autoInsertFill(JoinPoint joinPoint) {
        try {
            // 1. 获取原始方法的参数
            Object[] args = joinPoint.getArgs();
            Object object = args[0];
            // 2. 给这个参数赋值
            // 获取类的Class对象
            Class<?> clazz = object.getClass();

            // 获取名为setMyProperty的方法
            Method setCreateTime = clazz.getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = clazz.getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateUser = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            // 准备要传递给setter方法的参数
            LocalDateTime now = LocalDateTime.now();
            Long currentId = BaseContext.getCurrentId();

            // 调用setter方法并传入参数
            setCreateTime.invoke(object, now);
            setUpdateTime.invoke(object, now);
            setCreateUser.invoke(object, currentId);
            setUpdateUser.invoke(object, currentId);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }


    @Pointcut("@annotation(com.sky.annotation.AutoUpdateFill)")
    public void update() {

    }

    @Before("update()")
    public void autoUpdateFill(JoinPoint joinPoint) {
        try {
            // 1. 获取原始方法的参数
            Object[] args = joinPoint.getArgs();
            Object object = args[0];
            // 获取类的Class对象
            Class<?> clazz = object.getClass();

            // 获取名为setMyProperty的方法
            Method setUpdateTime = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            // 准备要传递给setter方法的参数
            LocalDateTime now = LocalDateTime.now();
            Long currentId = BaseContext.getCurrentId();

            // 调用setter方法并传入参数
            setUpdateTime.invoke(object, now);
            setUpdateUser.invoke(object, currentId);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}
